/*
 * Copyright (c) 2019, Beijing Aegean Soft. All rights reserved.
 *
 */

package com.inoteexpress.irpdataexport;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/*
 * Excel 操作类，利用POI的API合成Excel文件
 * @author  Sunny
 * @date 2019/03/16
 */

@Service
public class ExcelExportService {
    public void exportXls(List<Map<String, Object>> list, String[] heads, String filePath) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("咨询数据");
        HSSFRow headRow = sheet.createRow(0);
        for (int idx = 0; idx < heads.length; idx++) {
            headRow.createCell(idx).setCellValue("dc." + heads[idx]);
        }
        //循环在execl中放入数据
        for (Map<String, Object> row : list) {
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
            for (int idx = 0; idx < heads.length; idx++) {
                String value = (String) row.get(heads[idx]);
                if (value != null && value.length() > 32000) {
                    value = value.substring(0, 32000);
                }
                dataRow.createCell(idx).setCellValue(value);
            }
        }
        FileOutputStream fos = new FileOutputStream(filePath);
        workbook.write(fos);
        workbook.close();
        fos.flush();
        fos.close();
    }
}
